package hndx.AutoTestWeb.service;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributeView;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;

import ch.ethz.ssh2.StreamGobbler;
import hndx.AutoTestWeb.VO.FileItemVO;

@Service
public class MainService {
	public RunState doState=RunState.INIT;
	private String exportPath="./export";
	private int MAX_FILES = 20;
	private String CHARSET = "GBK";
	public enum RunState{
		INIT,DOING,DOWN
	}
	
	public MainService() {
		
	}
	public String runAutoTest(HttpServletResponse response) {
		synchronized(this) {
			if(doState == RunState.DOING) {
				String temp = "执行中，不能重复执行!";
				System.out.println(temp);
				return temp;
			}
			doState = RunState.DOING;
		}
		
		Process process = null;
		String command = "java -jar AutoTest-0.0.1-SNAPSHOT.jar export";
		String commandRet="",commandError="";
		try {
			process = Runtime.getRuntime().exec(command);
			commandRet = processStdout(process.getInputStream(),CHARSET,response);
			if("".equals(commandRet)) {
				commandError = processStdout(process.getErrorStream(),CHARSET,response);
			}
			process.waitFor();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		synchronized(this) {
			doState = RunState.DOWN;
		}
		return "".equals(commandRet) ? commandError:commandRet;
	}
	public List<FileItemVO> getResultFiles(){
		File file=null,subfiles[];
		List<FileItemVO> retlist = new ArrayList<FileItemVO>();
		
		file =new File(exportPath);
				
		subfiles = file.listFiles();
		int i=0;
		BasicFileAttributeView basicview=null;
		BasicFileAttributes attr=null;
		for(File cur : subfiles) {
			basicview = Files.getFileAttributeView(Paths.get(cur.getPath()),BasicFileAttributeView.class,LinkOption.NOFOLLOW_LINKS);
			try {
				attr = basicview.readAttributes();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			FileItemVO vo = new FileItemVO();
			vo.fileName = cur.getName();
			vo.fileSize = cur.length()/1024+"K";
			vo.createTime = formatFileTime(attr.creationTime());
			retlist.add(vo);
			i++;
			if(i >= MAX_FILES)break;
		}
		Collections.sort(retlist);
		return retlist;
	}
	public String getStateStr() {
		String ret="";
		if(this.doState == RunState.INIT) {
			ret = "未开始";
		}else if(this.doState == RunState.DOING) {
			ret = "执行中";
		}else if(this.doState == RunState.DOWN) {
			ret = "已完成";
		}else {
			ret = "未定义";
		}
		return ret;
	}
	public String getCurPath() {
		File file =new File(exportPath);
		
		return file.getAbsolutePath();
	}
	
	private String processStdout(InputStream in, String charset,HttpServletResponse response){        
		 InputStream  stdout = new StreamGobbler(in);        
		 StringBuffer buffer = new StringBuffer();;        
		 try {
			 BufferedReader br = new BufferedReader(new InputStreamReader(stdout,charset));
			 String line=null;
			 PrintWriter writer=null;
			 if(response != null) {
				 writer = response.getWriter();
			 }
			 while((line=br.readLine()) != null){                
				 buffer.append(line+"\n"); 
				 if(writer != null) {
					 writer.print(new String(line.getBytes("UTF-8"))+"\n");
					 writer.flush();
				 }
			 }
		 } catch (UnsupportedEncodingException e) {                     
			 e.printStackTrace();        
		 } catch (IOException e) {                      
		     e.printStackTrace();        
		 }
		 return buffer.toString(); 
	}
	public static String formatFileTime(FileTime intime) {
		String retval="";
		Date date=new Date(intime.toMillis());
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		retval=format.format(date);
		return retval;
	}
}
